package com.cms.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.cms.model.Language;
import com.cms.service.LanguageService;
import com.cms.service.LanguageServiceImpl;

public class LanguageManager {

	private static LanguageManager instance = null;
	public static synchronized LanguageManager getInstance()
	{
		if (instance == null)
		{
			instance = new LanguageManager();
		}
		return instance;
	} 
	
	private LanguageService service;
	private Map<String,Language> lMap;
	private Object lock = new Object();
	
	private String maxId="0";
	
	protected LanguageManager()
	{
		service = new LanguageServiceImpl();
		lMap = new HashMap<String, Language>();
		
		List<Language> llist = service.getAll();
		if(llist!=null&&llist.size()>0)
		{
			for (Language l : llist) {
				lMap.put(l.getId(), new Language(l));
			}
			maxId = service.getMaxId();
		}
	}
	
	public List<Language> getAll()
	{
		List<Language> list = new ArrayList<Language>();
		for (Entry<String,Language> e : lMap.entrySet()) {
			list.add(new Language(e.getValue()));
		}
		return list;
	}
	
	public Language getById(String id)
	{
		if(lMap.containsKey(id))
			return new Language(lMap.get(id));
		return null;
	}
	
	public boolean insert(Language t)
	{
		synchronized(lock)
		{
			t.setId((Integer.parseInt(maxId)+1)+"");
			if(service.insert(t))
			{
				maxId = (Integer.parseInt(maxId)+1)+"";
				lMap.put(maxId, new Language(t));
				return true;
			}
		}
		return false;
	}
	
	public boolean update(Language t)
	{
		String id = t.getId();
		if(!lMap.containsKey(id))
			return false;
		
		Language type = getById(t.getId());
		if(type==null || !type.getId().equals(t.getId()))
			return false;
		
		synchronized (lock) {
			if(service.update(t))
			{
				lMap.get(id).setName(t.getName());
				lMap.get(id).setRemark(t.getRemark());
				
				return true;
			}
		}
		return false;
	}
	
	public boolean delete(Language t)
	{
		String id = t.getId();
		if(!lMap.containsKey(id))
			return false;
		
		synchronized (lock) {
			if(service.delete(t))
			{
				lMap.remove(id);
				return true;
			}
		}
		return false;
	}
}
